package com.test.config.shiro;

import com.test.entity.Users;
import com.test.utils.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class TokenFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {


        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String token = httpServletRequest.getHeader("token");
        Users users = (Users)SecurityUtils.getSubject().getPrincipal();

        //校验是否登录并且是否存在token
        if(users != null || isLoginRequest(request, response))
        {
            return Boolean.TRUE;
        }else{
            users = TokenUtil.getUsersInfo(token);
            if(users != null || isLoginRequest(request, response))
            {
                return Boolean.TRUE;
            }

        }
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //保存Request和Response 到登录后的链接
        saveRequestAndRedirectToLogin(request, response);
        return Boolean.FALSE ;
    }
}
